package com.csrcb.tools;

import com.csrcb.constant.EmsInfoUrlValue;
import com.csrcb.constant.ParamConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

/**
 * @Classname HttpSendContent
 * @Description 原生的http的get和post请求，全程使用jdk自带的api，日志除外
 * @Date 2020/12/16 9:17
 * @Created by gangye
 */
public class HttpSendContent {
    private static Logger logger = LoggerFactory.getLogger(HttpSendContent.class);

    /**
     * 使用post发送请求
     *
     * @param requestUrl     请求的路由
     * @param requestBodyStr 请求体报文
     * @return
     */
    public static String doPost(String requestUrl, String requestBodyStr, String contentType, String acceptType, Map<String, String> headInfo) {
        OutputStreamWriter osw = null;
        BufferedReader br = null;
        StringBuilder result = new StringBuilder();
        HttpURLConnection conn = null;
        try {
            URL url = new URL(requestUrl);
            //通过远程url连接对象打开一个连接，强转成HTTPURLConnection类
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(ParamConstant.POST_REQUEST_METHOD);
            //发送post请求必须设置为true
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //设置连接超时事件和去读超时时间
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(10000);
            conn.setRequestProperty("Content-Type", contentType);
            conn.setRequestProperty("Accept", acceptType);
            //增加请求头信息
            if (headInfo != null && !headInfo.isEmpty()){
                for(String key : headInfo.keySet()){
                    conn.setRequestProperty(key, headInfo.get(key));
                }
            }
            //获取输出流
            osw = new OutputStreamWriter(conn.getOutputStream());
            osw.write(requestBodyStr);
            osw.flush();
            osw.close();
            //取得输入流
            if (200 == conn.getResponseCode()) {
                br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String line;
                while ((line = br.readLine()) != null) {
                    result.append(line);
                    logger.info("doPost方法的请求返回的报文：{}", result);
                }
            } else {
                logger.error("ResponseCode is an error code:{}", conn.getResponseCode());
            }
        } catch (MalformedURLException e) {
            logger.error("请求的url：{}异常", requestUrl);
        } catch (IOException ie) {
            logger.error("流处理异常异常");
        } finally {
            try {
                StreamHandler.handleCloseStream(osw, br);
            } catch (IOException e) {
                logger.info("最终流关闭失败！");
            }
        }
        return result.toString();
    }

    public static String doGet(String requestUrl, String acceptType, Map<String, String> headInfo) {
        InputStream is = null;
        BufferedReader br = null;
        StringBuilder result = new StringBuilder();
        HttpURLConnection conn = null;
        try {
            URL url = new URL(requestUrl);
            //通过远程url连接对象打开一个连接，强转成HTTPURLConnection类
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(ParamConstant.GET_REQUEST_METHOD);
            //设置连接超时事件和去读超时时间
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(10000);
            conn.setRequestProperty("Accept", acceptType);
            conn.setRequestProperty("Token",EmsInfoUrlValue.getQueryemstoken());
            //增加请求头信息
            if (headInfo!=null && !headInfo.isEmpty()){
                for(String key : headInfo.keySet()){
                    conn.setRequestProperty(key, headInfo.get(key));
                }
            }
            //发送请求
            conn.connect();
            //取得输入流
            if (200 == conn.getResponseCode()) {
                is = conn.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String line;
                while ((line = br.readLine()) != null) {
                    result.append(line);
                    logger.info("doGet方法的请求返回的报文：{}", result);
                }
            } else {
                logger.error("ResponseCode is an error code:{}", conn.getResponseCode());
            }
        } catch (MalformedURLException e) {
            logger.error("请求的url：{}异常", requestUrl);
        } catch (IOException ie) {
            logger.error("流处理异常异常");
        } finally {
            try {
                StreamHandler.handleCloseStream(is, br);
            } catch (IOException e) {
                logger.info("最终流关闭失败！");
            }
            conn.disconnect();
        }
        return result.toString();
    }
    //还可以会用apache的http请求jar工具实现get与post请求
    //参考https://www.jianshu.com/p/117264481886
}
